<template>
    <el-card>
        <el-form :model="queryParams" ref="queryParams" :inline="true" label-width="100px">
            <el-form-item label="角色名称：" prop="roleName">
                <el-input v-model="queryParams.roleName" placeholder="角色名称" size="small"></el-input>
            </el-form-item>
            <el-form-item label="角色别名：" prop="roleAlias">
                <el-input v-model="queryParams.roleAlias" placeholder="角色别名" size="small"></el-input>
            </el-form-item>
             <el-form-item >
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-delete" size="small" @click="resetQuery('queryParams')">清空</el-button>
            </el-form-item>
        </el-form>
            <el-row :gutter="10">
                <el-col :span="24">
                    <div style="margin-bottom: 10px">
                        <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
                        <el-button type="danger" plain icon="el-icon-delete" size="small" @click="handleDelete(multipleSelection)">删除</el-button>
                        <el-button icon="el-icon-setting" size="small" @click="powerSetting">权限设置</el-button>
                    </div>
                </el-col>
            </el-row>
           <el-table
            :data="tableData"
            style="width: 100%;margin-bottom: 20px;"
            row-key="id"
            ref="table"
            border
            default-expand-all
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
             @selection-change="handleSelectionChange"
            size="small">
             <el-table-column
                type="selection"
                width="55">
             </el-table-column>
            <el-table-column
            prop="roleName"
            label="角色名称"
           >
            </el-table-column>
            <el-table-column
            prop="roleAlias"
            label="角色别名"
            >
            </el-table-column>
            <el-table-column
            prop="sort"
            label="角色排序">
            </el-table-column>
             <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                      <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-view"
                    @click="handleView(scope.row)">查看</el-button>
                    <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-edit"
                    @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
          </el-table-column>
        </el-table>
            <el-dialog :title="formTitle" :visible.sync="roleFormVisible">
                <el-form :model="form" :rules="rules" ref="form" :disabled="isView">
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item  prop="roleName" label="角色名称" :label-width="formLabelWidth" required>
                                <el-input v-model="form.roleName" autocomplete="off" size="mini" placeholder="请输入角色名称"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                     <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item  prop="roleAlias" label="角色别名" :label-width="formLabelWidth" required>
                                <el-input v-model="form.roleAlias" autocomplete="off" size="mini" placeholder="请输入角色别名"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                     <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item  prop="ip" label="上级角色" :label-width="formLabelWidth">
                                <el-select v-model="form.parentId" placeholder="请选择上级菜单" size="mini" style="width: 100%">
                                     <el-input
                                            placeholder="输入关键字进行过滤"
                                            style="padding: 10px;width: 96%"
                                            size="mini"
                                            v-model="filterText">
                                        </el-input>
                                        <el-option :value="parentValue" :label="parentLabel" style="height: auto">
                                        <el-tree ref="tree" :data="selectTreeData" highlight-current :filter-node-method="filterNode" @node-click="handleNodeClick"></el-tree>
                                    </el-option>
                               </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                     <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item  prop="sort" label="角色排序" :label-width="formLabelWidth" required>
                                <el-input-number v-model="form.sort" placeholder="请输入角色排序" size="mini" style="width: 100%"></el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="handleSubmit('form')" size="small">保存</el-button>
                    <el-button @click="handleClose('form')" size="small">取消</el-button>
                </div>
            </el-dialog>
             <el-dialog title="角色权限设置" :visible.sync="powerVisible">
                 <el-tabs type="border-card">
                    <el-tab-pane label="菜单权限">
                        <el-tree
                            :data="menuData"
                            show-checkbox
                            node-key="id"
                            :default-checked-keys="defaultMenuChecked">
                        </el-tree>
                    </el-tab-pane>
                    <el-tab-pane label="数据权限">
                          <el-tree
                            :data="dataScopeData"
                            show-checkbox
                            node-key="id"
                            :default-checked-keys="defaultScopeData">
                        </el-tree>
                    </el-tab-pane>
                    <el-tab-pane label="接口权限">
                         <el-tree
                            :data="apiScopeData"
                            show-checkbox
                            node-key="id"
                            :default-checked-keys="defaultApiData">
                        </el-tree>
                    </el-tab-pane>
                 </el-tabs>
                <div slot="footer" class="dialog-footer">
                     <el-button @click="powerVisible = false" size="small">取消</el-button>
                     <el-button type="primary" @click="handlePower" size="small">确定</el-button>
                </div>
             </el-dialog>
    </el-card>
</template>

<script>

import { getRoleList,getParentTree,saveRole,getGrantTree,getTreeKeys,delRole,savePower } from '@/api/authority/role.api.js'
    export default {
       data() {
           return {
                tableData: [],
                queryParams: {
                    current: 1,
                    size: 10,
                    roleName: undefined,
                    roleAlias: undefined
                },
                formTitle: '新增',
                roleFormVisible: false,
                form: {},
                rules: {
                    roleName: [
                      { required: true, message: '请输入角色名称', trigger: 'blur' },
                    ],
                    roleAlias: [
                      { required: true, message: '请输入角色别名', trigger: 'blur' },
                    ],
                    sort: [
                      { required: true, message: '请输入角色排序', trigger: 'blur' },
                    ],
                },
                formLabelWidth: '100px',
                selectTreeData: [],
                filterText: '',
                parentLabel: '',
                parentValue: '',
                multipleSelection: [],
                powerVisible: false,
                menuData: [],
                dataScopeData: [],
                apiScopeData: [],
                defaultMenuChecked: [],
                defaultScopeData: [],
                defaultApiData: [],
                isView: false
                
           }
       },
        watch: {
            filterText(val) {
                this.$refs.tree.filter(val);
            }
        },
        mounted() {
          this.getTableData();
        },
        methods: {
            // 搜索
            handleQuery() {
                this.queryParams.current = 1;
                this.getTableData();
            },
            // 清空
            resetQuery(formName) {
                this.$refs[formName].resetFields();
                this.getTableData();
            },
           async getTableData() {
                const result = await getRoleList(this.queryParams)
                if(result.code === 200) {
                    this.tableData = result.data;
                }
            },
            async handleAdd() {
                this.roleFormVisible = true;
                this.isView = false;
                this.formTitle = '新增';
                const result = await getParentTree();
                if(result.code === 200) {
                    this.selectTreeData = this.getTreeNode(result.data);
                }
            },
            getTreeNode(data) {
                data.forEach(item => {
                    item.label = item.title;
                    if(item.hasChildren) {
                        this.getTreeNode(item.children);
                    }
                });
                return data;
           },
            handleNodeClick(data) {
                this.parentLabel = data.label;
                this.parentValue = data.value;
                this.form.parentId = data.value;
            },
             filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            handleClose(formName) {
                this.roleFormVisible = false;
                this.$refs[formName].resetFields();
            },
            handleSubmit(formName) {
                   this.$refs[formName].validate(async (valid) => {
                    if (valid) {
                        const data = this.form;
                        data.$parentId = this.parentLabel;
                        const result = await saveRole(data);
                        if(result.code === 200) {
                             this.$message({
                                message: '保存成功',
                                type: 'success'
                            });
                            this.roleFormVisible = false;
                             this.getTableData();
                        }
                    } else {
                        console.log('error submit!!');
                       
                        return false;
                    }
                    });
            },
            handleDelete(ids) {
                let roleIds;
                typeof ids === 'string'?roleIds=ids:roleIds=ids.map(item=>item.id).toString();
                this.$confirm('确定将选择的数据删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(async () => {
                        const result = await delRole(roleIds);
                        if(result.code === 200) {
                             this.$message({
                                type: 'success',
                                message: '删除成功!'
                           });
                           this.getTableData();
                        }
                    }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 权限设置
            async powerSetting() {
                if(this.multipleSelection.length !== 1) {
                      this.$message({
                        message: '只能选择一条数据',
                        type: 'warning'
                      });
                    return false;
                }
                const result = await getGrantTree();
                if(result.code === 200) {
                    this.menuData = this.getTreeNode(result.data.menu);
                    this.dataScopeData = this.getTreeNode(result.data.dataScope);
                    this.apiScopeData = this.getTreeNode(result.data.apiScope);
                }
                const result2 = await getTreeKeys(this.multipleSelection[0].id); 
                if(result2.code === 200) {
                    this.defaultMenuChecked = result2.data.menu;
                    this.defaultScopeData = result2.data.dataScope;
                    this.defaultApiData = result2.data.apiScope;
                }
                this.powerVisible = true;
            },
            async handlePower() {
                let data = {
                    apiScopeIds: this.apiScopeData,
                    dataScopeIds: this.dataScopeData,
                    menuIds: this.menuData,
                    roleIds: this.refs.table
                }
                const result = await savePower();
            },
            async handleEdit(row) {
                console.log(row);
                this.formTitle = '编辑';
                this.isView = false;
                this.form = row;
                const result = await getParentTree();
                 if(result.code === 200) {
                    this.selectTreeData = this.getTreeNode(result.data);
                 }
                this.parentLabel = row.parentName;
                this.parentValue = row.parentId;
                this.roleFormVisible = true;
            },
            async handleView(row) {
                this.formTitle = '查看';
                this.isView = true;
                this.form = row;
                const result = await getParentTree();
                 if(result.code === 200) {
                    this.selectTreeData = this.getTreeNode(result.data);
                 }
                this.parentLabel = row.parentName;
                this.parentValue = row.parentId;
                this.roleFormVisible = true;
            }
        },
        
      
    }
</script>

<style lang="scss" scoped>
.el-select-dropdown__item {
    padding: 0;
}
</style>